package cn.huolabao.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Set;

@Component
public class JwtCheckFilter implements GlobalFilter, Ordered {

    private final StringRedisTemplate redisTemplate;

    @Value("${authorization.urls:/admin/auth/login,/admin/auth/kaptcha,/admin/auth/logout}")
    private Set<String> noNeedTokenUrls;

    @Autowired
    public JwtCheckFilter(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        if (!needToken(exchange)) {
            return chain.filter(exchange);
        }

        String token = getUserToken(exchange);
        if (StringUtils.isEmpty(token)) {
            return buildNoAuthorizationError(exchange);
        }
        Boolean hasKey = redisTemplate.hasKey(token);
        if (!ObjectUtils.isEmpty(hasKey) && hasKey) {
            return chain.filter(exchange);
        }
        return buildNoAuthorizationError(exchange);
    }

    private Mono<Void> buildNoAuthorizationError(ServerWebExchange exchange) {
        ServerHttpResponse httpResponse = exchange.getResponse();
        HttpHeaders httpResponseHeaders = httpResponse.getHeaders();
        httpResponseHeaders.set("Content-Type", "application/json");
        httpResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "20001");
        jsonObject.put("message", "token无效");
        jsonObject.put("result", null);
        jsonObject.put("success", false);
        DataBuffer wrap = httpResponse.bufferFactory().wrap(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8));
        return httpResponse.writeWith(Flux.just(wrap));
    }

    private String getUserToken(ServerWebExchange exchange) {
        String token = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        return token.replace("Bearer ", "");
    }

    private boolean needToken(ServerWebExchange exchange) {
        return !noNeedTokenUrls.contains(exchange.getRequest().getURI().getPath());
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
